import Vue from 'vue'
import Vuex from 'vuex'
import {
	LOGIN_STATUS,
	UID,
	USER_INFO,
	USER_INFO_ROLE,
	CACHE_USER_AVATAR
} from '../config/cache';
import Cache from '../utils/Cache'

import {
	request
} from '../request/index.js'
import api from '../common/js/api';
import utils from '../utils/utils.js'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token:Cache.get(LOGIN_STATUS),
		calcElmtClientHeight: '',
		userSelectBankInfo:{},
		hasLogin: false,
		userInfo: {},
		userInfoRole: {},
		entryType: 0,
		thirdUserInfo: {},
		shopCarNumber: 0,
		reqFlag: true, //购物车页面 是否需要请求
		isCartToPay: false, //是否从购物车页面购买
		socketTask: null, // websocket
		isNavBackSpecifyPage: uni.getStorageSync('isNavBack') || false,
		longitude:'',
		latitude:'',
		count: 0
	},
	getters: {
		longitude: state => state.longitude,
		latitude: state => state.latitude,
		token: state => state.token,
		isLogin: state => !!state.token,
		entryType: state => state.entryType,
		calcElmtClientHeight: state => state.calcElmtClientHeight,
		userSelectBankInfo: state => state.userSelectBankInfo,
		userInfo: state => state.userInfo || {},
		userInfoRole: state => state.userInfoRole || {},
		uid:state => state.app.uid,
		// 带参数的getter
		countPlus: (state, getters) => (add) => {
			return state.count + add;
		}
	},
	mutations: {

		increment(state, payload) {
			state.count += payload.amount;
		  }
,	  
		LONGITUDE(state, opt) {
			state.longitude = opt.longitude;
			Cache.set(LONGITUDE, opt.longitude);
		},
		LATITUDE(state, opt) {
			state.latitude	 = opt.latitude;
			Cache.set(LATITUDE, opt.latitude);
		},
		// 登录
		LOGIN(state, opt) {
			state.token = opt.token;
			Cache.set(LOGIN_STATUS, opt.token, opt.time);
		},

        UPDATE_USERINFO(state, userInfo) {
            state.userInfo = userInfo;
            Cache.set(USER_INFO, userInfo);
        },
        UPDATE_USERINFO_ROLE(state, userInfo) {
            state.userInfo = userInfo;
            Cache.set(USER_INFO_ROLE, userInfo);
        },
		SETUID(state, val) {
			state.uid = val;
			Cache.set(UID, val);
		},
		// 退出登录
		LOGOUT(state) {
			state.token = false;
			state.isLogin = false;
			state.uid = 0
			Cache.clear(LOGIN_STATUS);
			Cache.clear(USER_INFO);
			Cache.clear("OPENID");
			Cache.clear("roution_authorize_state");
			Cache.clear(UID);
			Cache.clear('snsapiCode');
		},

		setBankInfo(state,data){
			state.userSelectBankInfo = data;
		},
		// setElmtHeight(state, e) {
		// 	state.calcElmtClientHeight = e;
		// },
		loginSave(state, provider) {
			console.log(provider);
			state.hasLogin = true;
			state.userInfo = provider;
			uni.setStorageSync('token', provider.token); //这里用同步方法存储，但是在request中 getStorage异步获取 也能获取到，0.0
			uni.setStorageSync('userInfo', provider);
		},
		setIsNavBackSpecifyPage(state, data) {
			uni.setStorageSync('isNavBack', data);
			state.isNavBackSpecifyPage = data;
		},
		// setStorageKey(state,data){
		// 	uni.setStorageSync(data.key,data.val);
		// },
		modifyEntryType(state, data) {
			state.entryType = data;
		},
		saveThirdUserInfo(state, data) {
			state.thirdUserInfo = data;
			uni.setStorage({ //缓存用户登陆状态
				key: 'thirdUserInfo',
				data: data
			})
		},
		setCarNum(state, num) {
			state.shopCarNumber = num;
		},
		setUserInfo(state, data) {
			state.userInfo = data;
		},
		login(state, provider) {
			state.reqFlag = true;
			state.hasLogin = true;
			state.userInfo = provider;
			uni.setStorage({ //缓存用户登陆状态
				key: 'userInfo',
				data: provider
			})
		},
		logout(state) {
			state.hasLogin = false;
			state.userInfo = {};
			state.thirdUserInfo = {};
			state.reqFlag = true;
			uni.removeStorage({
				key: 'userInfo'
			});
			uni.removeStorage({
				key: 'thirdUserInfo'
			});
			uni.removeStorageSync('first_order');
			uni.removeStorageSync('limitorder_count');
			uni.removeStorageSync('order_count');
			uni.removeStorageSync('no_pay_count');
			uni.removeStorageSync('new_people_count');
		},
		updateReqFlag(state) {
			state.reqFlag = false;
		},
		updateReqFlagTwo(state) {
			state.reqFlag = true;
		},
		setSocketTask(state, data) {
			state.socketTask = data;
		},
		updatePayEntrance(state, flag) {
			state.isCartToPay = flag;
		}
	},
	actions: {
		//顶部元素与小程序胶囊居中的位置处理；
		//备注 css 无法获取胶囊的信息  只能获取 顶部状态栏status-bar  所以使用js方式获取
		calcElementInfoVx({
			commit,
			state
		}, data) {
			return new Promise((resolve, reject) => {
				//获取设备宽度
				let pageWidth = uni.getWindowInfo().screenWidth;
				// console.log(data.elementId);
				//获取小程序胶囊按钮的位置信息
				let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
				let calcPtTop = menuButtonInfo.top + 3 + 'px'; // 配合居中显示 固定值改为3 - 20240730
				//获取设置icon的位置信息
				const elmt = uni.createSelectorQuery().in(data.vue);
				let calcTop, calcRight, calcElmtClientHeight;
				elmt.select(data.elementId).boundingClientRect(rect => {
					console.log("rect",rect)
					calcTop = menuButtonInfo.top + (menuButtonInfo.height - rect.height) / 2 +
						'px'; //为了自定义区域与胶囊居中
					calcRight = pageWidth - menuButtonInfo.left + 6 + 'px'; //此处的6为固定值作为边距
					calcElmtClientHeight = menuButtonInfo.top + menuButtonInfo.height +
						'px'; //顶部固定区域下面section内容的marginTop

					if (!state.calcElmtClientHeight) {
						uni.setStorageSync('calcElmtClientHeight', calcElmtClientHeight);
						state.calcElmtClientHeight = calcElmtClientHeight;
					}

					resolve({
						calcPtTop,
						calcTop,
						calcRight,
						calcElmtClientHeight
					})
				}).exec();
			});
		},
		commitGoods({
			commit,
			state
		}, data) {
			request({
				url: api.changeCart,
				method: "post",
				isLogin: true,
				data: data,
			}).then(res => {
				utils.showToast("加入购物车成功");
				console.log(res);
				state.shopCarNumber = res.data.cart_count;
				state.reqFlag = true;
			})
		},
		commitCollect({
			commit,
			state
		}, data) {
			request({
				url: api.editCollection,
				method: "post",
				isLogin: true,
				data: {
					goods_id: data.goods_id
				},
			}).then(res => {
				if (res.code == 200) {
					if (!data.isShowToast) {
						utils.showToast(res.message, 'none');
					}
					data.success(res);
				}
			})
		},
		toGoodsDetail({
			commit,
			state
		}, data) {
			let id = data.goods_id || data.id;
			let sku_id = data.sku_list ? data.sku_list.id : data.sku_id ? data.sku_id : 0;
			// let sku_id = data.sku_id ? data.sku_id : data.sku_list.id ? data.sku_list.id : 0;
			let order_count = uni.getStorageSync('order_count') || uni.getStorageSync('limitorder_count');
			let no_pay_count = uni.getStorageSync('no_pay_count');
			let new_people_count = uni.getStorageSync('new_people_count');
			// let limitorder_count=uni.getStorageSync('limitorder_count');
			let type = data.type;
			console.log(113, type, order_count, no_pay_count, new_people_count);
			if (type == 11) { //如果是新人专区
				if (no_pay_count != 0 && new_people_count == 0) { //没有判断活动,先这么写
					uni.showModal({
						content: '您在新人专区有一笔订单未支付，需要直接付款或者取消订单重新购买哦',
						success: res => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/order/order?state=0'
								})
							}
						}
					});
				} else if (new_people_count != 0) {
					uni.showModal({
						content: '您已达到最大购买限量',
						showCancel: false
					});
				} else if (order_count != 0) {
					uni.showModal({
						content: '您已不是新用户了',
						showCancel: false
					});
				} else {
					uni.navigateTo({
						url: `/pages/goods/detail?goods_id=${id}&sku_id=${sku_id}`
					})
				}
			} else if (type == 12) {
				if (order_count < 1) {
					uni.showModal({
						content: '限时特惠仅限第二单购买哦！',
						showCancel: false
					});
				} else if (order_count >= 2) {
					uni.showModal({
						content: '您已完成了两个订单,不可以在限时特惠下单了哦!',
						showCancel: false
					});
				} else {
					uni.navigateTo({
						url: `/pages/goods/detail?goods_id=${id}&sku_id=${sku_id}`
					})
				}
			} else {
				uni.navigateTo({
					url: `/pages/goods/detail?goods_id=${id}&sku_id=${sku_id}`
				})
			}


		}
	}
})

export default store
